<template>
  <view class="whole" >
  <index-header-xhd
    class="index-header-xhd"
    :currentIndex="currentIndex" 
    :currentRecommendNavIndex="currentRecommendNavIndex" 
    @updateIndex="updateCurrentIndex" 
    @updateNavIndex="updateCurrentRecommendNavIndex"
  ></index-header-xhd>
  <view
    class="indexContent"
  >
	  <view v-if="currentIndex === 1">
	      <!-- 推荐内容部分 -->
	      <view v-if="currentRecommendNavIndex === 1">
			 <dynamic-list-xhd
			 class="list"
			 :itemList="recommendedPosts"
			 :viewHeight="viewHeight"
			 :itemHeight="130"
			 :loadCount="loadCount" 
			 :fetchData="fetchRecommendedPosts"
			 :needRefresh="true"
			 :startRefreshOnce="fetchDataOnce"
			 >
			 <template v-slot:item="{ item }" >
				 <recommended-post-xhd
				    :item="item" 
				    :key="item.id"
				    :post="item"  
				    @postClicked="goBlogDisply"
				 ></recommended-post-xhd>
			 </template>
			 </dynamic-list-xhd>
	      </view>
		  <view v-else>
			  <view v-if="uid!=-1">
					<scroll-view
					  class="scroll-view-following"
						scroll-y="true"
						lower-threshold="10"
					  	:refresher-enabled="couldRefreshFollowing"
						@scroll="onScrollFollowing"
						@scrolltolower="getFollowingPostsMore"
						:refresher-triggered="isRefreshingFollowing"
						@refresherrefresh="onRefreshFollowing"
						refresher-default-style="none"	
					>
					<view class="refresh-following"  slot="refresher">
						<image class="refreshGif-following" src="/static/gif/refresh_yu_1.gif"></image>
					</view> 
					    	<view v-if="followingPosts.length > 0">
					    	  <view>
					    	    <view  v-for="(post,index) in followingPosts" :key="index">
					    	      <recommended-post-xhd
					    	      	:item="post"
					    	      	:key="index"
					    	        :post="post"
					    	        @postClicked="goBlogDisply"
					    	       ></recommended-post-xhd>
					    	    </view>
					    	  </view>
					    	</view>
					    	<view v-else class="null">没有找到任何博客哦</view>
					  </scroll-view>
			  </view>
			  <view v-else class="null">
					您还没有登录，请先登录再查看此页面
			  </view>
		  </view>
	  </view>

	  <view v-show="currentIndex === 0">
		  <scroll-view
		      class="scroll-view"
		      scroll-y="true"
		      lower-threshold="10"
		      :refresher-enabled="couldRefresh"
		      @scroll="onScroll"
		      @scrolltolower="getMore"
		      :refresher-triggered="triggered"
		      @refresherrefresh="onRefresh"
			  @refresherpulling="livePulling"
			  @refresherabort="liveAbort"
			  @refresherrestore="liveStore"
		      refresher-default-style="none"
		  >
		      <view class="refresh" slot="refresher">
		          <image class="refreshGif" :src="loadingSrc"></image>
		      </view>
		      <view v-if="dynamicPost.length > 0">
		          <view class="columns">
		              <view class="column" v-for="columnIndex in 2" :key="columnIndex">
		                  <dynamic-post-xhd
		                      v-for="(post, index) in filteredPosts(columnIndex)"
		                      :key="post.id + '-' + index + '-dynamic'"
		                      :post="post"
		                      :index="index"
		                      :nowIndex="getNowIndex()"
		                      class="dynamicPost"
		                  ></dynamic-post-xhd>
		              </view>
		          </view>
		      </view>
		      <view v-else class="null">没有找到任何动态哦</view>
		  </scroll-view>
		</view>

   </view>
	
    <myTabBar  class="myTabBar"></myTabBar>
  </view>
</template>
<script>
import { mapState } from 'vuex';
import list from '../../uni_modules/uview-ui/libs/config/props/list';
import request from "../../utils/request.js";
import file from "../../utils/file.js";
export default {
  data() {
    return {
	  triggered:false,
      currentIndex: 0,
      currentRecommendNavIndex: 1,
	  viewHeight:0,
	  loadCount:10,
	  offset:0,
	  fetchDataOnce: true,
	  uid:null,
	  token:null,
	  followingBegin:0,
	  followingCount:5,
	  isRefreshingFollowing:false,
	  scrollViewTopFollowing:0,
	  couldRefreshFollowing:true,
	  dynamicPost: [],
	    couldRefresh: true,
	    scrollViewTop: 0,
	    batchSize: 10,
	    debounceTimer: null,
	  lastRefreshTime: '', // 存储上次刷新时间
	  begin:0,
	  count:5,//刷新动态的条数
	  c:0,
	  loadingSrc:"/static/gif/refresh_yu_0.gif",//加载图片
	  followingPosts:[],
	  recommendedPostRefresh:false,
	  defaultProfileImg: '/static/img/default-avatar.jpeg',
	  // listKey:0,
	  postsPerPage:5,//每次每页加载10条
	  recommendedPosts:[
		 // {
		 //    id: 1,
			// userId:4,
		 //    username: "余小平",
		 //    postTitle: "学习Java开发，加入海东之家",
		 //    postIntroduce: "yuxiaoping是人机，yuxiaoping是人机，yuxiaoping是人机，yuxiaoping是人机。",
		 //    profileImg: "../../static/img/test.jpg",
		 //    pictureImg: "../../static/img/test.jpg",
		 //    viewCount: 10,
		 //    likeCount: 5,
		 //    collectCount: 8,
		 //  },
	  ],
	  allPost:[],//全部动态的数组
    };
  },
async  mounted() {
	 //this.updateContentHeight();
    // 手机端取消
    uni.hideTabBar();
  },
  onLoad() {
	  const uid=uni.getStorageSync('UID')||null
	  if(uid==null){
		  this.uid=-1
	  }else{
		  this.token=uni.getStorageSync('token')
		  this.uid=uid;
	  }
    uni.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#f0f0f0',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    });
	this.initLive();
	this.calculateViewHeight();
	
  },
  methods: {
	getNowIndex(index){
		return this.scrollViewTop/200
	},
    updateCurrentIndex(index) {
      this.currentIndex = index;
	  if(index!=0){
		  // this.dynamicPost=[]
		  // this.begin=0
	  }
	  // console.log(index);
    },
    updateCurrentRecommendNavIndex(index) {
      this.currentRecommendNavIndex = index;
	  if(index!=0){
	  		  // this.followingPosts=[]
	  		  // this.followingBegin=0
	  }
	  console.log(index);
	//  console.log(index);
    },
	goBlogDisply(id){
		// const blog=this.recommendedPosts.find(post => post.id === id);
		// const blogString = JSON.stringify(blog);
		// const encodedBlogString = encodeURIComponent(blogString);
		// uni.navigateTo({
		//      url: `/pages/blogArticleDisplay/blogArticleDisplay?blog=${encodedBlogString}`
		// });
		//const blogId = this.recommendedPosts.find(post => post.id === id).id;
		
		uni.navigateTo({
		  url: `/pages/blogArticleDisplay/blogArticleDisplay?id=${id}`
		});
		
	},
	filteredPosts(columnIndex) {
	      // 根据列索引筛选帖子
	    return this.dynamicPost.filter((_, index) => index % 2 === columnIndex - 1);
	},
	calculateViewHeight() {
	    this.$nextTick(() => {
	        const query = uni.createSelectorQuery().in(this);
	        // 获取 index-header-xhd 的高度
	        query.select('.indexContent').boundingClientRect(headerData => {
	            this.viewHeight =headerData ? headerData.height : 0 ;
	            console.log('可用高度:', this.viewHeight);
	        }).exec();
	    });
	},
	async fetchFollowingPosts(count,type){
		return new Promise((resolve) => {
				console.log("请求关注的博客")
				setTimeout(()=>{
					this.followingPostRefresh=false
				},1500)
		});	
	},
	async fetchRecommendedPosts(count,type){
		return new Promise((resolve) => {
			console.log("type",type);
			if(this.fetchDataOnce){
				this.fetchDataOnce=false;
			}
			if(type==="refresh"){
				this.offset=0;
			}
				this.getData(count)
				    .then(result => {
				        if(result){
							if(result.code===1){
								console.log('Fetched data:',result.data );
							const newRecommendedPosts= result.data.map((item) => {
								let coverImage='loadingImg';
								
								let profileImg='loadingImg';
								// let profileImg=this.defaultProfileImg;
								const newPost={
									id: item.postId,
									userId:item.userId,
									username: item.authorName,
									postTitle: item.title,
									postIntroduce: item.blogDescribe,
									profileImg: profileImg,
									pictureImg: coverImage,
									viewCount: item.shareCount, // 浏览量
									likeCount: item.likesCount, // 点赞量
									collectCount: item.favoriteCount
								}
							    console.log(newPost);
							    return newPost; 
							});
							
							if(!newRecommendedPosts){
								newRecommendedPosts=[];
							}
							 if (type === 'loadMore') {
							    console.log("index加载数据");
							    newRecommendedPosts.forEach(newPost => {
							        const index = this.recommendedPosts.findIndex(post => post.id === newPost.id);
							        if (index > -1) {
							            this.recommendedPosts.splice(index, 1, newPost);
							        } else {
							            this.recommendedPosts.push(newPost);
							        }
							    });
							 }else if(type==="refresh"){
								 console.log("index刷新数据");
								 this.recommendedPosts=newRecommendedPosts;
								 //this.lastRefreshTime = new Date().toLocaleString();
								 //this.recommendedPostRefresh=true;
								 //resolve([]);
							}
							//console.log("加载的推荐博客是",newRecommendedPosts);
							//newRecommendedPosts
							console.log(this.recommendedPosts);
							this.offset+=this.recommendedPosts.length;
							resolve(newRecommendedPosts);
							}else{
								resolve([]);
							}
							
						}else{
							resolve([]);
						}
						//this.recommendedPostRefresh=false;
				    })
				    .catch(error => {
						resolve([]);
				        console.error('Error fetching data:', error);
				    });
				//console.log(result);
		    });	
			},
			
	async getData(count) {
		    const data = {
		        count: count,
				offset:this.offset
		    };
		    const userId = uni.getStorageSync('UID');
		    try {
		        let result;
		        if (userId) {
		            result = await request.sendUniPostRequestByNetWork(userId, undefined, "getRecommendedBlogs", data, "/post/getRecommendedBlogs");
		        } else {
		            result = await request.sendUniPostRequestByNetWork(undefined, undefined, "getRecommendedBlogs", data, "/post/getRecommendedBlogs");
		        }
				console.log("网络请求数据",result);
		        return result; // 返回结果
		    } catch (error) {
		        console.error('Error fetching data:', error);
		        throw error; // 抛出错误以便调用者处理
		    }
		},
		
		
		
		onRefreshFollowing(){
			console.log("当前加载路径"+this.loadingSrc)
			if(!this.isRefreshingFollowing){				
				// this.couldRefreshFollowing=false,
				this.isRefreshingFollowing=true;
				this.initFollowingPost()
				setTimeout(()=>{
					// uni.hideLoading()
					// this.couldRefreshFollowing=true
					this.isRefreshingFollowing=false;
					console.log("刷新完毕")
				},1000)
			}
		},
		initFollowingPost(){
			uni.request({
				url:this.baseUrl+"/post/getFollowingPost/"+this.uid+"/"+this.followingBegin+"/"+this.followingCount,
				method:"GET",
				header:{
					token:this.token,
					uid:this.uid
				},
				success: (res) => {
					const result=res.data
					console.log(res)
					if(res.data.code==1){
						result.data.forEach((item) => {
						    // 检查 item 是否为空对象
						    if (Object.keys(item).length === 0) return;
						    console.log(item);
						    let coverImage = 'loadingImg';
						    let profileImg = 'loadingImg';
						    
						    const newPost = {
						        id: item.blog.postId,
						        userId: item.blog.userId,
						        username: item.username,
						        postTitle: item.blog.title,
						        postIntroduce: item.blog.blogDescribe,
						        profileImg: profileImg,
						        pictureImg: coverImage,
						        viewCount: item.blog.shareCount, // 随机浏览量
						        likeCount: item.blog.likesCount, // 随机点赞量
						        collectCount: item.blog.favoriteCount
						    };
						    
						    console.log(newPost);
						    this.followingPosts.unshift(newPost);
						    // 更新成功！
						    this.followingBegin = this.followingPosts.length;
						});

					}else{
						console.log("关注用户的博客加载失败")
					}
				},
				complete: () => {

						// console.log("加载路径:"+this.loadingSrc)
						// console.log("这是第"+this.c+"张加载图")
				}
			})
		},
		getFollowingPostsMore(){
			
		},
		onScrollFollowing(event){
				const { scrollTop, scrollHeight, clientHeight } = event.target;
				this.scrollViewTopFollowing = scrollTop;
				// console.log(this.scrollViewTop)
					  if(this.scrollViewTopFollowing==0){
						  this.couldRefreshFollowing=true;
					  }else{
						  this.couldRefreshFollowing=false;
					  }
		},
						
		
				getMore(){
					uni.showLoading({
						title:"加载动态……"
					})
					var uid=uni.getStorageSync('UID')||(-1)
					console.log("用户uid=",uid)
					console.log("请求起始postId:"+this.begin)
					uni.request({
						url:this.baseUrl+"/live/getRecommendLive/"+uid+"/"+this.begin+"/"+this.count,
						method:"GET",
						success: (res) => {
							if(res.data.code==1){
								console.log("收到返回结果：")
								console.log(res.data.data)
								if(res.data.data.length==0){
									this.isRefreshing=false
									uni.showToast({
										title:"已经没有新动态了！！!",
										icon:"none",
										duration:500
									})
									return;
								}
								res.data.data.forEach((data)=>{
									console.log(data)
									var imgs=[];
									data.base64Images.forEach(image => {
									    const imgBase64 = image.base64;
									    const imgExtension = image.extension;
												
									    // 连接成 Data URL
									    const imgType = imgExtension; // 使用后缀名作为 MIME 类型
									    const dataUrl = "data:image/" + imgType + ";base64," + imgBase64;
												
									    // 将 Data URL 添加到 this.photos 数组
									    imgs.push(dataUrl);
									});
									const imgBase64 = data.avatar.userAvatar;
									const imgExtension = data.avatar.imgType;
											
									// 连接成 Data URL
									const imgType = imgExtension; // 使用后缀名作为 MIME 类型
									const dataUrl = imgType + ";base64," + imgBase64;
									
									this.dynamicPost.push({
									    id: data.post.postId,
									    uid: data.post.userId,
										profileImg:dataUrl,
									    imgs: imgs,
									    dynamicContent: data.post.content,
									    username: data.username,
									    likeCount: data.post.likesCount
									});
								})
							}else{
					
							}
							this.begin=this.dynamicPost.length;
							this.count=3
						},
						complete: () => {
							uni.hideLoading()
						}
					})
				},
		 livePulling(){
			console.log("Live下拉中") 
		 },
		 liveAbort(){
			 console.log("Live下拉被中断") 
		 },
		 liveStore(){
			 console.log("Live下拉回复") 
		 },
		 onRefresh() {
			 console.log("触发一次动态加载");
			 // uni.showLoading({
			 //     title: "数据加载中……"
			 // });
			 this.triggered = true;
			  this.initLive();
			  setTimeout(() => {
			       this.triggered = false;
				   // uni.hideLoading();
				   console.log("动态刷新完毕");
				   this.c = (this.c + 1) % 7;
				   this.loadingSrc = "/static/gif/refresh_yu_" + this.c + ".gif";
			 }, 1000)
		    },
		    
		    initLive() {
		        var uid = uni.getStorageSync('UID') || (-1);
		        console.log("刷新动态中……");
		         uni.request({
		            url: this.baseUrl + "/live/getRecommendLive/" + uid + "/" + this.begin + "/" + this.count,
		            method: "GET",
		            success: (res) => {
		                if (res.data.code == 1) {
		                    if (res.data.data.length == 0) {
		                        this.begin = this.dynamicPost.length;
		                        uni.showToast({
		                            title: "已经没有新动态了！！!",
		                            icon: "none",
		                            duration: 3000
		                        });
		                        return;
		                    }
		                    res.data.data.forEach((data) => {
		                        var imgs = [];
		                        data.base64Images.forEach(image => {
		                            const imgBase64 = image.base64;
		                            const imgExtension = image.extension;
		                            const imgType = imgExtension; // 使用后缀名作为 MIME 类型
		                            const dataUrl = "data:image/" + imgType + ";base64," + imgBase64;
		                            imgs.push(dataUrl);
		                        });
		                        const imgBase64 = data.avatar.userAvatar;
		                        const imgExtension = data.avatar.imgType;
		                        const imgType = imgExtension; // 使用后缀名作为 MIME 类型
		                        const dataUrl = imgType + ";base64," + imgBase64;
		
		                        this.dynamicPost.unshift({
		                            id: data.post.postId,
		                            uid: data.post.userId,
		                            profileImg: dataUrl,
		                            imgs: imgs,
		                            dynamicContent: data.post.content,
		                            username: data.username,
		                            likeCount: data.post.likesCount
		                        });
		                    });
		                }
		                this.begin = this.dynamicPost.length;
		                this.count = 5;
		            },
		            fail: (res) => {
		                console.error("请求失败:", res);
		            },
		            complete(res){
		                this.couldRefresh = true; 
		            }
		        });
		    },
		
			onScroll(event) {
			    // 计算当前滚动位置
			    const { scrollTop, scrollHeight, clientHeight } = event.target;
			    this.scrollViewTop = scrollTop;
				// console.log(this.scrollViewTop)
					  if(this.scrollViewTop==0){
						  this.couldRefresh=true;
					  }else{
						  this.couldRefresh=false;
					  }
			},
  },
  computed: {
    ...mapState(["username"]),
    displayedContent() {
      if (this.currentIndex === 0) {
        return "动态内容"; // 替换为实际的动态内容
      } else if (this.currentIndex === 1) {
        return this.currentRecommendNavIndex === 0 ? "关注内容" : "全部内容";
      } else if (this.currentIndex === 2) {
        return "热榜内容"; // 替换为实际的热榜内容
      }
      return ""; // 默认返回空
    }
  } ,
  watch: {
	 // currentIndex() {
	 //         this.calculateViewHeight();
		// 	 console.log(1112);
	 //     },
	 //     currentRecommendNavIndex() {
	 //         this.calculateViewHeight();
			 
	 //     },
		  recommendedPosts(newValue) {
		     // 当 recommendedPosts 更新时执行的逻辑
		    // console.log("推荐文章更新:", newValue);
			//this.listKey++;
			 this.recommendedPosts =newValue; // 直接替换整个数组
		   }
  },

  mounted(){
	  
	  this.currentIndex=0;
	 
  },
  onShow() {
  	 //this.recommendedPostRefresh=false;
  }
}
</script>

<style lang="scss">
.whole {
  display: flex;
 flex-direction: column; // 确保子元素垂直排列
  height: 100vh;
  background-color: #f0f0f0;
 
.indexContent{
	 
  	 flex: 1; // 使内容区域占据剩余空间
	// display: flex;
	 overflow-y: auto;
  	background-color:  #f0f0f0;
  	margin-bottom: 130rpx;
	.columns {
	  margin-top: 5rpx;
	  display: flex;
	 // background-color: red;
	  justify-content: space-around;
	  .column {
		width: 47%;
	    flex: 1;
	    margin:0 10rpx;
		box-sizing: border-box; /* 确保内边距和边框包含在宽度内 */
	    .dynamicPost {
	      margin-bottom: 10px;
	      padding: 10rpx;
	      border: 1rpx solid #ccc;
	      background-color: #f9f9f9;
	    }
	  }
	  }
  }
  .myTabBar {
    width: 100%;
    height: 130rpx;
    position: fixed;
    bottom: 0;
    background-color: #fff;
    box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
    z-index: 1000;
  }
}
.null{
	color: lightgray;
	font-size: 30rpx;
	text-align: center;
	margin-top: 500rpx;
	margin-bottom: 800rpx;
}
.scroll-view{
	// background-color: red;
	height: 80vh;
	width: 100%;
}
.scroll-view-following{
	// background-color: lawngreen;
	height: 75vh;
	width: 100%;
}
.refresh{
	overflow: hidden;
	height: 40px;
}
.refresh-following{
	overflow: hidden;
	height: 30px;
}
.refreshGif-following{
	display: block; /* 使图片作为块级元素 */
	width: 30%; /* 宽度设为容器的80%，可以根据需要调整 */
	max-width: 30px; /* 最大宽度设为100px，避免图片过大 */
	max-height: 30px; /* 最大高度设为100px，避免图片过高 */
	margin: 0 auto; /* 水平居中 */
	object-fit: contain; /* 保持图片比例，防止拉伸 */
}
.refreshGif {
  display: block; /* 使图片作为块级元素 */
  width: 30%; /* 宽度设为容器的80%，可以根据需要调整 */
  max-width: 40px; /* 最大宽度设为100px，避免图片过大 */
  max-height: 40px; /* 最大高度设为100px，避免图片过高 */
  margin: 0 auto; /* 水平居中 */
  object-fit: contain; /* 保持图片比例，防止拉伸 */
}

</style>

<!--  <scroll-view
      class="indexContent"
      :scroll-y="true"
    >
	  <view v-if="currentIndex === 1">
	      <view v-if="currentRecommendNavIndex === 1">
	          <recommended-post-xhd 
	              v-for="(post, index) in recommendedPosts" 
	              :key="post.id" 
	              :post="post"  
	              @postClicked="goBlogDisply"
	          ></recommended-post-xhd>
	      </view>
	  </view>
	  <view v-else-if="currentIndex === 0" >
	  	  <view class="columns">
	  	    <view class="column" v-for="columnIndex in 2" :key="columnIndex">
	  	      <dynamic-post-xhd
	  	        v-for="(post, index) in filteredPosts(columnIndex)"
	  	        :key="post.id + '-' + index + '-dynamic'" 
	  	        :post="post"
	  	        class="dynamicPost"
	  	      ></dynamic-post-xhd>
	  	    </view>
	  	  </view>
	  </view>
    </scroll-view> -->